package com.loe.ui.api

import android.webkit.JavascriptInterface
import com.loe.ui.key
import com.loe.ui.registerFun
import com.loe.ui.view.UiViewPager
import com.quickjs.JSObject

class ViewPagerApi(private val view: UiViewPager) : ViewGroupApi(view)
{
    @JavascriptInterface
    fun getIndex(child: JSObject): Int = view.currentItem

    init
    {
        jsObject.registerFun("select")
        {
            val p = it.get(0)

            fun toSelect(i: Int)
            {
                val smooth = if (it.length() > 1) it.getBoolean(1) else true
                view.setCurrentItem(i, smooth)
            }

            if (p is JSObject)
            {
                view.viewList.forEachIndexed()
                { i, v ->
                    val o = (v as IUiView).jsObject
                    if (p.key == o.key)
                    {
                        toSelect(i)
                    }
                }
            } else
            {
                toSelect(p as Int)
            }
        }
    }
}